﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.Text.RegularExpressions;

namespace BoAddonBiz_FreightForwarder.Sea
{
    class B1Form_SE_SEDLForm : SAPBoAddon.B1Form
    {
        private const string AVA_SE_SEDL = "@AVA_SE_SEDL";
        private const string AVA_SE_SEDL1 = "@AVA_SE_SEDL1";
        public B1Form_SE_SEDLForm()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_SE_SEDLForm_frm_ItemEvent);
        }
        #region 继承基类
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
            switch (frmEditMode)
            {
                case SAPBoAddon.frmItemEditMode.fe_AddMode:

                    CurrentForm.Freeze(true);
                    //自动添加操作日期
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_SE_SEDL);
                    /*操作员，客服相关*/
                    dynamic Operator = Utils.GetCurrentUser();
                    dbds.SetValue("U_Operator", dbds.Offset, Operator.Operator);
                    dbds.SetValue("U_OperatorCode", dbds.Offset, Operator.empID);
                    dbds.SetValue("CreateDate", dbds.Offset, DateTime.Now.ToString("yyyyMMdd"));
                    dbds.SetValue("UserSign", dbds.Offset, SBOCompany.UserSignature.ToString());
                    dbds.SetValue("U_CustomClearClass", dbds.Offset, "Normal");
                    dbds.SetValue("U_TransMode", dbds.Offset, "SEAFREIGHT");
                    dbds.SetValue("U_TradeMode", dbds.Offset, "Normal Trade");
                    dbds.SetValue("U_ServiceType", dbds.Offset, "STANDARD");
                    
                    CurrentForm.Freeze(false);
                    break;
            }
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            this.FormSetting.FormType = B1FormTypes.ado_AVA_SE_SEDLForm;
            this.FormSetting.FormFileName = "AVA_SE_SEDLForm.srf";
            //FormSetting.OpenVisiable = true;//默认打开显示
            this.FormSetting.AutoGetObjectNextNumber = true;
            #region 表格设置
            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_SE_SEDL1";
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.AffectsFormModeAddRow = true;
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.addButtonUID = "add";
            FormSetting.MatrixSetting.delButtonUID = "del";
            FormSetting.MatrixSetting.Add();
            #endregion
            FormSetting.FormModeSetting.itmNewModeDisable = new string[] { "67" };
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_3", "DocCurrCod", "CurrName", "OCRN");//订单金额币种

            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && new Regex(@"\b\d+\b").Match(InitPar.FatherFormUID).Success)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, InitPar.FatherFormUID);
                this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
        }
        #endregion
        #region 事件处理
        void B1Form_SE_SEDLForm_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {

            }
            else
            {
                if (pVal.ItemUID == "23" && pVal.ItemChanged && pVal.EventType == SAPbouiCOM.BoEventTypes.et_VALIDATE
                    && (this.CurrentForm.Mode == SAPbouiCOM.BoFormMode.fm_ADD_MODE || this.CurrentForm.Mode == SAPbouiCOM.BoFormMode.fm_UPDATE_MODE))
                {
                    this.GetBPInfo();
                }
            }
        }

        #endregion
        #region 私有函数
        /// <summary>
        /// 获取业务单信息
        /// </summary>
        private void GetBPInfo()
        {
            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_SE_SEDL);
            string str_HAWB = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "23").ToString();
            string SQL_BP = string.Format(@"SELECT 
T0.U_MBLNumber,U_ShipsName as U_Flight,T0.U_Quantity,T0.U_GrossWeight,T0.U_BillingWeight,T0.U_ETD,T0.U_ATD,T0.U_ETA,T0.U_ATA,T0.U_TransportType,T0.U_EndPortThCode,
        T1.U_CargoType,T3.U_Sender,UPPER(T0.U_StartPort) AS StartPort,UPPER(T5.U_CountryNameE) as  U_CountryNameE,T1.U_BookingDate,
                                                                    T0.U_BookingAgentName,T0.U_Bargain,T3.U_BoxCode
                                                                    FROM [@AVA_SE_OBNO] T0 
                                                                   INNER JOIN [@AVA_SE_BNO1] T1 ON T0.DocEntry=T1.DocEntry
                                                                   INNER JOIN [@AVA_SE_BNO4] T3 ON T0.DocEntry=T3.DocEntry
                                                                   INNER JOIN [@AVA_FF_PORT] T5 ON ISNULL(T0.U_StartPortCode,N'')=T5.Code 
                                                                   WHERE T0.U_SBLNumber=N'{0}' ", str_HAWB);
            SAPbobsCOM.Recordset oRs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            oRs.DoQuery(SQL_BP);

            string[] Dic_BPFieldtoSEDLField = new string[] { "U_MBLNumber-U_MBLNumber", "U_Flight-U_Flight", "StartPort-U_StartPort", "U_CountryNameE-U_StartPortENamel","U_Quantity-U_Quantity","U_GrossWeight-U_GrossWeight",
            "U_BillingWeight-U_BillingWeight", "U_ETD-U_ETD","U_ATD-U_ATD","U_ETA-U_ETA","U_ATA-U_ATA","U_Sender-U_Sender",
            "U_BookingAgentName-U_Forwarder","U_TransportType-U_TransMode","U_CargoType-U_CargoType", "U_EndPortThCode-U_EndPortThCode" ,
            "U_BookingDate-U_PickUpDate","U_Bargain-U_Incoterm","U_BoxCode-U_ContainerNo"
            };
            // "PickupDate-xxxx","ReleaseDate-xxxxx", "DeliveryDate-xxxx",,"U_ServiceType-U_ServiceType"

            if (oRs.RecordCount > 0)
            {
                object BP_Value = null;
                foreach (string field in Dic_BPFieldtoSEDLField)
                {
                    BP_Value = oRs.Fields.Item(field.Split('-')[0]).Value;

                    if (BP_Value.GetType() == typeof(DateTime))
                    {
                        if (((DateTime)BP_Value).Year <= 1900)
                        {
                            dbds.SetValue(field.Split('-')[1], 0, string.Empty);
                        }
                        else
                        {
                            dbds.SetValue(field.Split('-')[1], 0, string.Format("{0:yyyyMMdd}", BP_Value));
                        }

                    }
                    else
                    {
                        if (field.Split('-')[0] == "U_TransportType" && BP_Value.ToString() == "AIBJ")
                        {
                            dbds.SetValue(field.Split('-')[1], 0, "Air Freight");
                        }
                        else
                        {
                            dbds.SetValue(field.Split('-')[1], 0, BP_Value.ToString());
                        }

                    }
                }
            }
            else
            {
                foreach (string field in Dic_BPFieldtoSEDLField)
                {
                    dbds.SetValue(field.Split('-')[1], 0, string.Empty);
                }
            }

        }
        #endregion
    }
}
